package com.ant.storage.service.impl;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ConverterUtils;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.ant.storage.dto.InventoryExcelDto;
import com.ant.storage.pojo.Commodity;
import com.ant.storage.pojo.Inventory;
import com.ant.storage.service.IInventoryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author hzd
 * @version 1.0
 * @date 2023/5/30 15:27
 */
@Slf4j
@Service
public class GoodsListener implements ReadListener<InventoryExcelDto> {

    @Autowired
    private IInventoryService inventoryService;


    private List<InventoryExcelDto> goodsExcelDTOList = ListUtils.newArrayList();
    private final List<Inventory> inventoryList = ListUtils.newArrayList();
    private int count = 0;

    public GoodsListener() {
    }

    public GoodsListener(IInventoryService inventoryService) {
        this.inventoryService = inventoryService;
    }

    // 2. 第二解析内容
    @Override
    public void invoke(InventoryExcelDto inventoryExcelDto, AnalysisContext analysisContext) {
        log.info("解析到第 {} 条数据:{}", (++count), JSON.toJSONString(inventoryExcelDto));
        goodsExcelDTOList.add(inventoryExcelDto);
    }

    // 1. 第一先读表头
    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        Map<Integer, String> stringMap = ConverterUtils.convertToStringMap(headMap, context);
        Set<Integer> keySet = stringMap.keySet();
      //  System.out.println("该Excel表头信息是：");
        for (int i = 0; i < keySet.size(); i++) {
            System.out.println("第 " + (i + 1) + " 列 = " + stringMap.get(i));
        }
    }

    // 3. 第三解析额外信息
    //    public void extra(CellExtra extra, AnalysisContext context){
    //        return null;
    //    }

    // 4. 最后调用
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("该Excel的所有数据解析完成！！！");
        goodsExcelDTOList.forEach(item -> {
            try {
                Inventory inventory = new Inventory();
                inventory.setWarehouseId(item.getWarehouseId());
                // 先判断商品是否存在
                Commodity one = inventoryService.getOneCommodityId(item.getCommodityBarCode());
                inventory.setCommodityId(one.getCommodityId()==null?1:one.getCommodityId());
                inventory.setGoodsAmount(new BigDecimal(item.getGoodsAmount()).setScale(2,BigDecimal.ROUND_HALF_UP));
                inventory.setGoodsPrice(new BigDecimal(item.getGoodsPrice()));
                inventoryList.add(inventory);

            } catch (ParseException e) {
                log.error(e.getMessage());
            }
        });
        goodsExcelDTOList = ListUtils.newArrayList();
        inventoryList.stream().forEach(item->{
            //判断是否存在库存
            Inventory one = inventoryService.getOne(new QueryWrapper<Inventory>().
                     eq("warehouse_id",item.getWarehouseId())
                    .eq("commodity_id",item.getCommodityId()));
            if(one==null){
                //不存新增
                item.setCreationTime(new Date());
                item.setCreatorBy("admin");
                item.setGoodsPrice(new BigDecimal(String.valueOf(item.getGoodsPrice())));
                inventoryService.save(item);
                inventoryService.insertLog(item);
            }else{
                //存在修改数量和价格
                Inventory inventory=new Inventory();
                inventory.setId(one.getId());
                inventory.setGoodsAmount(item.getGoodsAmount());
                inventory.setGoodsPrice(new BigDecimal(String.valueOf(item.getGoodsPrice())));
                //Double total_Num = Double.parseDouble(one.getGoodsAmount()) + Double.parseDouble(item.getGoodsAmount());
                //inventoryService.inventoryUpate(total_Num.toString(),one);
                inventoryService.updateById(inventory);
                item.setId(one.getId());
                inventoryService.insertLog(item);
            }
        });
       // inventoryService.saveBatch(inventoryList);
    }

}
